<template>
  <div class="login-wrap">
    <el-row type="flex" justify="space-around">
      <el-col :span="12" >
        <div class="login-box">
          <el-row>
            <el-col :span="10" v-loading="ctrLoading" element-loading-text="拼命加载中" element-loading-background="rgba(0, 0, 0, 0.8)">
              <div class="login-cont">
                <div class="login-tilte">
                  <img src="../assets/logo.png">
                </div>
                <el-form :model="loginForm" status-icon :rules="rules" ref="loginForm" class="login-form">
                  <el-form-item prop="phone">
                    <el-input v-model="loginForm.phone" maxlength="11" placeholder="登录手机号/机构编号"></el-input>
                  </el-form-item>
                  <el-form-item  prop="pass">
                    <el-input type="password" v-model="loginForm.pass" maxlength="24" placeholder="请输入密码" auto-complete="off"></el-input>
                  </el-form-item>
                  <el-row :gutter="20">
                    <el-col :span="14">
                      <el-form-item prop="verifykey">
                        <el-input maxlength="4" v-model="loginForm.verifykey" @keyup.enter.native="submitForm('loginForm')" placeholder="请输入图片数字"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="10">
                      <img :src="loginForm.imgcode" @click="getImgcode" id="codeimg" alt="" :style="{width:'84px',height:'40px'}"/>
                    </el-col>
                  </el-row>
                  <el-form-item>
                    <el-button type="primary" @click="submitForm('loginForm')" :loading="loading" style="width:100%">登录</el-button>
                    <!-- <el-button type="primary" @click="testToken" :loading="loading" style="width:100%">登录</el-button> -->
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
    <p style="position: absolute;bottom: 20px;text-align: center;width: 100%;color:#070707;font-size: 14px;">技术支持：杭州佐梦软件技术有限公司
    </p>

  </div>
</template>

<script>
import {
  fetchToken,
  fetchImgcode,
  getUserInfo,
  // isKey,
  fetchHomeToken
} from '@/api/login';
import { setToken } from '@/utils/auth';

export default {
  name: 'Login',
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    // var validatePhone = (rule, value, callback) => {
    //   if (!value) {
    //     callback(new Error('请输入正确的手机号码'));
    //   } else {
    //     const reg = /^1[3|4|5|7|8][0-9]\d{8}$/;
    //     if (!reg.test(value)) {
    //       callback(new Error('请输入正确的11位手机号码'));
    //     } else {
    //       callback();
    //     }
    //   }
    // };
    var vaildateNum = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入图片验证码'));
      } else {
        var len = value.length;
        if (len != 4) {
          callback(new Error('请输入图片验证码'));
        } else {
          callback();
        }
      }
    };
    return {
      ctrLoading:true,
      loginForm: {
        phone: '',
        pass: '',
        imgcode: '',
        verifykey: ''
      },
      rules: {
        // phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        pass: [{ validator: validatePass, trigger: 'blur' }],
        verifykey: [{ required: true, validator: vaildateNum, trigger: 'blur' }]
      },
      loading: false
    };
  },
  created() {
    this.getHomeToken();
  },
  methods: {
    submitForm(formName) {
      let that = this;
      that.$refs[formName].validate(valid => {
        if (valid) {
          that.loading = true;
          fetchToken(
            that.loginForm.phone,
            that.loginForm.pass,
            that.loginForm.verifykey,
            'gov'
          )
            .then(data => {
              that.loading = false;
              if (data.token) {
                setToken(data.token);
                //获取用户数据
                getUserInfo()
                  .then(data => {
                    var myData = JSON.stringify(data.data); //转化为JSON字符串
                    if (localStorage.hasOwnProperty('token')) {
                      localStorage.removeItem('token');
                    }
                    localStorage.setItem('UserInfo', myData);
                    that.$router.push({ path: '/' });
                  })
                  .catch(function(error) {
                    console.log(error);
                    that.loading = false;
                    that.loginForm.pass = '';
                    return true;
                  });
              }
            })
            .catch(function(error) {
              console.log(error);
              that.loading = false;
              that.loginForm.pass = '';
              that.loginForm.verifykey = '';
              that.getImgcode();
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getImgcode() {
      let that = this;
      fetchImgcode()
        .then(data => {
          var n = data.data;
          var src = 'data:image/jpg;base64,' + n;
          that.loginForm.imgcode = src;
        })
        .catch(function(error) {
          console.log(error);
          that.loginForm.pass = '';
          that.loginForm.verifykey = '';
        });
    },
    getHomeToken() {
      let that = this;
      fetchHomeToken()
        .then(data => {
          if (data.token) {
            localStorage.setItem('token', data.token);
            this.ctrLoading=false;
            that.getImgcode();

          } else {
            new Error('获取用户识别码失败，请刷新页面后重新获取！');
          }
        })
        .catch(function(error) {
          console.log(error);
          that.loginForm.pass = '';
          that.loginForm.verifykey = '';
        });
    }
    // // 验证码
    // isvalidKey(str) {
    //   isKey(str)
    //     .then(data => {
    //       console.log('check ', data);
    //       return true;
    //     })
    //     .catch(function(error) {
    //       console.log(error);
    //       return false;
    //     });
    //   return false;
    // }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style rel='stylesheet/scss' lang="scss" scoped>
@import 'src/styles/mixin.scss';

.login-wrap {
  background: #0c75c1;
  height: 100%;
}

.login-box {
  margin-top: 200px;
  background: url('http://or.dc.zjmade.cn/static/login-bg2.jpg') no-repeat
    bottom 0 right -110px;
}

.login-tilte {
  margin-bottom: 20px;
  position: relative;
  z-index: 1;
}

.login-tilte img {
  display: block;
  width: 100%;
  margin: auto;
  z-index: -1;
}

.login-cont {
  box-sizing: border-box;
  padding: 30px;
  background: #fff;
}

#codeimg {
  width: 100%;
  display: block;
}

.somelink {
  @include clearfix;
  a {
    display: block;
    color: #999;
    font-size: 14px;
  }
  .getpassword {
    float: left;
  }
  .register {
    float: right;
  }
}
</style>
